#!/usr/bin/env python
# -*- coding: utf-8 -*-


from ConfigParser import ConfigParser
import json
import time

from engine import singleton
from dm_py_util import ERROR_LOG, DEBUG_LOG

from .sql_manager import SQLManager

class SQLCluster():

    def __init__(self):
        self.cluster_number = 0
        self.manager_cluster = []

    def init(self, config):
        self.config = config
        cfg = ConfigParser()
        cfg.read(config)

        self.cluster_number = int(cfg.get('Cluster', 'num'))

        for i in range(self.cluster_number):
            try:
                manager_config = cfg.get('Cluster_%d' % i, 'config')
                manager = SQLManager()
                manager.init(manager_config)
            except Exception as e:
                ERROR_LOG('init manager error', e)
                raise Exception('cluster init manager error')
            if not manager:
                raise Exception('cluster init manager error')
            self.manager_cluster.append(manager)

        if not len(self.manager_cluster):
            raise Exception('no avaliable manager in cluster')

        if len(self.manager_cluster) != self.cluster_number:
            raise Exception('cluster number and cluster manager len donnot match')

        DEBUG_LOG('SQLCluster init success...')


    def get_manager(self, idx):
        if len(self.manager_cluster) and idx < self.cluster_number:
            return self.manager_cluster[idx]

        return None


if __name__ == '__main__':
    c = SQLCluster()
    c.init('./conf/cluster.ini')

    m = c.get_manager(0)
    print m

    m = c.get_manager(10)
    print m

    print m.query('show tables')
